package com.genesis.mall.service.impl;

import com.genesis.mall.dto.PmsProductCategoryDto;
import com.genesis.mall.entity.PmsProductCategory;
import com.genesis.mall.mapper.PmsProductCategoryMapper;
import com.genesis.mall.service.IPmsProductCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.genesis.mall.service.IPmsProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 产品分类 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-08-01
 */
@Service
public class PmsProductCategoryServiceImpl extends ServiceImpl<PmsProductCategoryMapper, PmsProductCategory> implements IPmsProductCategoryService {
    @Autowired
    private PmsProductCategoryMapper pmsProductCategoryMapper;

    //查询商品分类的级联信息
    @Override
    public List<PmsProductCategoryDto> getAll1() {
        return pmsProductCategoryMapper.getAll();
    }

   @Override
    public List<PmsProductCategory> getAll() {
        //获取所有菜单
        List<PmsProductCategory> categoryList = list();
        //存储根节点菜单
        ArrayList<PmsProductCategory> rootCategoryList = new ArrayList<>();
        //遍历菜单
        for (PmsProductCategory pmsProductCategory : categoryList) {
            if (pmsProductCategory.getParentId()==0){
                rootCategoryList.add(pmsProductCategory);
            }
        }
        //为根节点设置子菜单
        for (PmsProductCategory pmsProductCategory : rootCategoryList) {
            //获取根节点下的所有子节点
            List<PmsProductCategory> childrenList =getChild(pmsProductCategory.getId(),categoryList);
            //根节点设置子节点
            pmsProductCategory.setChildren(childrenList);
        }

        return rootCategoryList;
    }

    //查询所有菜单
    private List<PmsProductCategory> getChild(Long id, List<PmsProductCategory> categoryList) {
        //子菜单
        ArrayList<PmsProductCategory> childList = new ArrayList<>();
        //遍历所有菜单
        for (PmsProductCategory pmsProductCategory : categoryList) {
            //传入的id 与当前菜单的父类id相等 则添加到集合中
            if (id.equals(pmsProductCategory.getParentId())){
                childList.add(pmsProductCategory);
            }
        }
        //递归设置子节点
        for (PmsProductCategory pmsProductCategory : childList) {
            pmsProductCategory.setChildren(getChild(pmsProductCategory.getId(),categoryList));
        }
        //如果节点下没有子节点 返回一个空集合,递归退出
        if (childList.size()==0){
            return new ArrayList<PmsProductCategory>();
        }
        return childList;
    }
}
